package com.huoyun.user.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.huoyun.base.action.BaseAction;
import com.huoyun.car.model.CarUserCompanyModel;
import com.huoyun.car.service.CarService;
import com.huoyun.cargo.model.CargoUserCompanyModel;
import com.huoyun.cargo.service.CargoService;
import com.huoyun.user.bean.User;
import com.huoyun.user.service.UserService;
import com.huoyun.util.IpUtil;
import com.opensymphony.xwork2.ActionContext;


public class UserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6568242316372289344L;
	
	private static final Log log = LogFactory.getLog(UserAction.class);
	/**
	 * salt 的长度
	 */
	private static final int SALT_LENGTH = 8;

	private UserService userService;
	
	
	private PasswordEncoder passwordEncoder;
	
	private AuthenticationManager authenticationManager;
	
	/**
	 * 账户类型
	 */
	private String accountType;
	
	/**
	 * 老密码
	 */
	private String oldPassword;
	
	/**
	 * 新密码
	 */
	private String newPassword;
	
	/**
	 * 校验码
	 */
	private String verifyCode;
	
	/**
	 * 确认密码
	 */
	private String verifyPassword;

	/**
	 * 用户对象
	 */
	private User user;
	
	
	
	
	public String index(){
		
		return SUCCESS;
	}
	
	public String preRegister()
	{
	
		return SUCCESS;
	}
	
	public String register()
	{
		
		String sessionVerifyCode = (String)getSession().getAttribute("verifyCode");
		//从session取出验证码后，将session中存放的验证码置为空
		getSession().setAttribute("verifyCode", "");
		
		verifyCode = (String)getRequest().getParameter("verifyCode");
		//对验证码进行校验
		if(!(verifyCode.toLowerCase()).equals(sessionVerifyCode.toLowerCase()))
		{
			this.setResultMsg("验证码输入错误");
			
			return INPUT;
		}
		
		//获取一个随机的字符串salt
		String randSalt = RandomStringUtils.random(SALT_LENGTH, true, true);
		
		//将用户输入的密码和随机生成的salt联合起来进行md5加密
		String saltPassword = passwordEncoder.encodePassword(user.getPassword(), randSalt);
		
		//用于用户注册完成之后的登录使用
		user.setOriginalPassword(user.getPassword());
		
		user.setSalt(randSalt);
		user.setPassword(saltPassword);
		
		user.setCheckBankAccount(false);
		user.setCheckEmail(false);
		user.setCheckMobilePhone(false);
		user.setCheckRealname(false);
		user.setEnabled(true);
		user.setLevel("1");
		user.setUserImg("/theme/images/user/default.gif");
		user.setRegisterIp(IpUtil.getIpAddr(getRequest()));
		
		try
		{
			int[] groupIds = new int[1];
			
			//如果用户注册的账户类型为货主
			if("1".equals(accountType))
			{
				groupIds[0] = 4;
			}
			else if("2".equals(accountType))
			{
				groupIds[0] = 3;
			}
			
			userService.saveUser(user, groupIds);
			
			//将当前注册的用户进行登录操作
			Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getOriginalPassword());
			//对用户信息进行鉴权
			authentication = authenticationManager.authenticate(authentication);
			//保存用户信息到当前的上下文中
			SecurityContextHolder.getContext().setAuthentication(authentication);
			
			log.info("用户【" + user.getUsername() + "】注册成功！");
		}catch (Exception e) {
			log.error("用户【" + user.getUsername() + "】注册失败！原因：" + e.fillInStackTrace());
			this.setResultMsg("系统忙，请稍后再试！");
			return ERROR;
		}
		
		//用户注册完成之后还没有设置权限
		getSession().setAttribute("isSaveRole", "0");
		
		return SUCCESS;
	}
	
	public String checkUser() throws IOException
	{
		this.setResultMsg("false");
		String username = "";
		
		if(user != null)
		{
			username = user.getUsername();
		}
		
		
		if(StringUtils.isNotEmpty(username))
		{
			try{
				User user = userService.getUserByUsername(username);
			
				if(user == null)
				{
					this.setResultMsg("true");
				}
			}catch (Exception e) {
				log.error("查询用户失败！UserAction - [checkUser]: Exception catched:" + e.getMessage());
			}
		
		}
		
		HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
		
		try
		{
			response.getWriter().print(this.getResultMsg());
		}catch (IOException e) {
			log.error("校验用户【"+ username +"】输出流发生错误！原因：" + e.fillInStackTrace());
			
			throw e;
		}
		return null;	
	}
	
	public String preLogin()
	{
		return SUCCESS;
	}
	
	public String login()
	{
		return SUCCESS;
	}
	
	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public String getVerifyCode() {
		return verifyCode;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}
	
	public String getVerifyPassword() {
		return verifyPassword;
	}

	public void setVerifyPassword(String verifyPassword) {
		this.verifyPassword = verifyPassword;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword; 
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getAccountType() {
		return accountType;
	}

	public void setAccountType(String accountType) {
		this.accountType = accountType;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

}
